﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using YunShop_WebAPI.Model;
using System.Web;
using NPOI.XWPF.UserModel;
using Flurl.Http;
using NPOI.SS.Formula.Functions;
using System.Web.Hosting;
using System.Net.Http.Headers;
using NPOI.Util;


namespace YunShop_WebAPI.BLL
{
    public class MallService
    {
        /// <summary>
        /// 获取广告数据== 
        /// </summary>
        /// <param name="DataType">0:轮番广告,1:广告位广告,2:分类导航</param>
        /// <returns></returns>
        public static ArrayList GetAdvList(int DataType, long CorpID, int TopNum = 0)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();

            strSql.AppendFormat(@"Exec pr_wap_GetAdvList @FCorpID,@FDataType,{0}", TopNum);
            ltpara.Add(new SqlParameter("@FCorpID", CorpID));
            ltpara.Add(new SqlParameter("@FDataType", DataType));
            string sql = strSql.ToString();
            return DBHelper.Select(sql, ltpara.ToArray(), DBHelper.ConnMaster);
        }


        public static ArrayList GetGoodsList(int mCorpID, int mPageIndex, int mPageSize, int mClassID, int mBrandID, string mConditon, int mOrderType)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.AppendFormat(@"Exec pr_wap_GetGoodFormClass  	@mPageSize ,@mPageIndex,@m_Member_Class_ID ,@mCorpID ,@mBrandID  ,@mOrderType  ,@mConditon");
            ltpara.Add(new SqlParameter("@mPageSize", mPageSize));
            ltpara.Add(new SqlParameter("@mPageIndex", mPageIndex));
            ltpara.Add(new SqlParameter("@m_Member_Class_ID", mClassID));
            ltpara.Add(new SqlParameter("@mCorpID", mCorpID));
            ltpara.Add(new SqlParameter("@mBrandID", mBrandID));
            ltpara.Add(new SqlParameter("@mOrderType", mOrderType));
            ltpara.Add(new SqlParameter("@mConditon", mConditon));
            string sql = strSql.ToString();
            return DBHelper.Select(sql, ltpara.ToArray(), DBHelper.ConnMaster);
        }



        public static async Task<Result_Model> LoginByPhoneOneKey(int m_CorpID, string m_code, string m_union_id, long m_stockID, string appid, int FParentID)
        {
            Dictionary<string, object> res;

            Dictionary<string, object> m_access_resp = await MallService.GetAccessTokenAsync(appid);
            int status = 0;
            SystemInfo.writeServiceLog("GetAccessTokenAsync", JsonConvert.SerializeObject(m_access_resp), "1", "1A", DBHelper.ConnMaster);

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string m_access_token = m_access_resp?["access_token"] as string;
                    string url = $"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={m_access_token}";

                    var jsonData = new
                    {
                        code = m_code,
                    };

                    string jsonString = JsonConvert.SerializeObject(jsonData);

                    StringContent content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    HttpResponseMessage response = await client.PostAsync(url, content);

                    response.EnsureSuccessStatusCode();
                    string result = await response.Content.ReadAsStringAsync();
                    res = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                    string m_errcode = JsonConvert.SerializeObject(res["errcode"]);

                    SystemInfo.writeServiceLog("getuserphonenumber", result, "2", "2B", DBHelper.ConnMaster);

                    if (m_errcode == "0")
                    {
                        Hashtable ht = new Hashtable();
                        Dictionary<string, object> m_phone_info = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(res["phone_info"]));
                        string m_phone_number = m_phone_info["purePhoneNumber"] as string;
                        string sql = @"SELECT  [FItemID],[FOpenID],[FCorpID],[FUserID],[FCreateTime],[FLoginTime],[FPhone],[FUnionID],[FNiName],[FGender],[FCity],[FProvince],[FCountry],[FAvatarUrl],[FHostID],[FSettingID],[FStockID],[FMemberID]  FROM [KingCloudShop].[dbo].[t_UserWeixin] where [FUnionID] = @FUnionID  and FCorpID = @FCorpID";
                        List<SqlParameter> ltpara = new List<SqlParameter>
                        {
                            new SqlParameter("@FUnionID", m_union_id),
                            new SqlParameter("@FCorpID", m_CorpID),

                        };
                        ArrayList userWx = DBHelper.Select(sql, ltpara.ToArray(), DBHelper.ConnMaster);
                        if (userWx.Count is 0)
                        {
                            return new Result_Model(status, "用户不存在！", "");
                        }

                        SystemInfo.writeServiceLog("queryUserWx", "用户不存在！", "3", "3C", DBHelper.ConnMaster);
                        Hashtable userWxInfo = userWx[0] as Hashtable;
                        string m_FPhone = userWxInfo["FPhone"] as string;
                        int? m_FUserID = userWxInfo["FUserID"] as int?;
                        long? m_FWeixinId = userWxInfo["FItemID"] as long?;
                        if (m_phone_number != null)
                        {

                            string eptStr = "";
                            // todo  这一段大改 , 使用unionID关联

                            /*
                                                        string m_sql = @"Exec pr_min_GetMemberLogin @FWxAppID,@FUnionID,@FOpenID,@FPhone,@FAvatarUrl,@FNickName,@FStockID";
                                                        SqlParameterList parlist = new SqlParameterList();
                                                        parlist.Add("@FWxAppID", SqlDbType.VarChar, appid);
                                                        parlist.Add("@FOpenID", SqlDbType.VarChar, m_phone_number);
                                                        parlist.Add("@FAvatarUrl", SqlDbType.VarChar, eptStr);
                                                        parlist.Add("@FUnionID", SqlDbType.VarChar, eptStr);
                                                        parlist.Add("@FNickName", SqlDbType.VarChar, eptStr);
                                                        parlist.Add("@FStockID", SqlDbType.BigInt, m_stockID);
                                                        DataSet ds = DBHelper.GetDataSet(m_sql, parlist.Get_List(), DBHelper.ConnMaster);
                            */
                            /*              if ((userWeixinDt == null) || (userWeixinDt.Rows.Count == 0))
                 {
                     m_sql = @"insert into t_UserWeixin(FCorpID,FOpenID,FCreateTime,FSettingID,FUnionID,FPhone,FNiName,FAvatarUrl,FStockID,FMemberID) 
values (@FCorpID,@FOpenID,GETDATE(),@FSettingID,@FUnionID,@FPhone,@FNickName,@FAvatarUrl,@FStockID,@FMemberID)";

                     DBHelper.ExeSQL(m_sql, new List<SqlParameter>() { new SqlParameter("@FCorpID", m_CorpID) }.ToArray(), DBHelper.ConnMaster);

                 }*/

                            string m_sql = @"Select * from t_UserWeixin where FUnionID = @FUnionID and FCorpID = @FCorpID";



                            // 获取会员分类
                            m_sql = @"Select * from t_MemberClass  where FCorpID = @mCorpId and FDeleted = 1  order by FDefault desc";
                            ArrayList m_Member_Class_List = DBHelper.Select(m_sql, new List<SqlParameter>() { new SqlParameter("@mCorpId", m_CorpID) }.ToArray(), DBHelper.ConnMaster);
                            long timeStamp = (DateTime.Now.Ticks) / 10000/10000;
                            DateTime now = DateTime.Now;
                            long m_Member_Class_ID = 0;
                            long m_member_ID = 0;
                            if (m_Member_Class_List.Count > 0)
                            {
                                m_Member_Class_ID = CommonFun.ConvertToBigInt((m_Member_Class_List[0] as Hashtable)["FItemID"]);
                            }
                            // 如果没有会员分类,插入会员分类
                            else
                            {
                                m_Member_Class_ID = GetMaxAutoID("t_MemberClass", "FItemID");
                                m_sql = "Insert Into dbo.t_MemberClass(FItemID, FParentID, FCorpID, FNumber, FName, FTypeID,  FDiscount, FPointFlag, FAmountFlag, FDeleted, FModifyTime, FCreateTime,FCardType) Values(@mClassID, 0, @mCorpId, @mClassID, '会员分类', 0,1, 1, 1, 1, @Timestamp, Getdate(),0); update t_DataExchangeList  set FLastID=@mClassID,FLastTime=@Timestamp where FCorpID=@mCorpId and FDatatype=8";
                                DBHelper.ExeSQL(m_sql, new List<SqlParameter>() {
                                    new SqlParameter("@mCorpId", m_CorpID),
                                    new SqlParameter("@mClassID", m_Member_Class_ID),
                                    new SqlParameter("@Timestamp", timeStamp) }.ToArray(), DBHelper.ConnMaster);
                            }


                            // 如果 t_Member 不存在 ,则插入 t_Member 和 t_Member_detail
                            m_sql = @"select * from t_Member where FCorpId=@mCorpId and FPhone=@mPhone and FDeleted=1";
                            ArrayList m_member_list = DBHelper.Select(m_sql, new List<SqlParameter>() {
                                    new SqlParameter("@mCorpId", m_CorpID),
                                    new SqlParameter("@mPhone", m_phone_number),
                                }.ToArray(), DBHelper.ConnMaster);
                            if (m_member_list.Count > 0)
                            {
                                m_member_ID = CommonFun.ConvertToBigInt((m_member_list[0] as Hashtable)["FItemID"]);
                            }
                            else
                            {
                                m_member_ID = GetMaxAutoID("t_Member", "FItemID");
                                m_sql = @"insert into t_Member(FItemID,FCorpID,FClassID,FPhone,FNumber,FName,FDiscount,FPoint  
		                 ,FPointFlag,FAmount,FAmountFlag,FPassword,FDeleted,FModifyTime,FQty)  
		                 values (@iMaxNo,@mCorpId,@m_Member_Class_ID,@mPhone,@mPhone,@mName,@Discount,0,  
		                 1,0,1,'IKh5dDSp8GJIN2z+h+2Hrg==',1,@Timestamp,0);

		                 insert into t_MemberDetail(FItemID,Fsex,FStartTime,FEndTime,FCreateTime,FAmount,FSheFlag,
		                 FSheAmount,FParentID,FSourceType,fk_users_id)  
		                 values (@iMaxNo,0,@date,@endDate,@date,0,0,0,0,2,0);
                         exec pr_bi_CouponGive @mCorpId,@iMaxNo,'';
		                update t_DataExchangeList set FLastID=@iMaxNo,FLastTime=@Timestamp where FCorpID=@mCorpId and FDataType=9
";

                                DateTime endDate = now.AddYears(100);
                                DBHelper.ExeSQL(m_sql, new List<SqlParameter>() {
                                    new SqlParameter("@iMaxNo", m_member_ID),
                                    new SqlParameter("@mCorpId", m_CorpID),
                                    new SqlParameter("@m_Member_Class_ID",m_Member_Class_ID  ),
                                    new SqlParameter("@mPhone", m_phone_number),
                                    new SqlParameter("@mName", m_phone_number),
                                    new SqlParameter("@Discount", m_Member_Class_List.Count > 0? ((m_Member_Class_List[0])as Hashtable)["FDiscount"]:1),
                                    new SqlParameter("@Timestamp", timeStamp),
                                    new SqlParameter("@date", now),
                                    new SqlParameter("@endDate", endDate),
                                }.ToArray(), DBHelper.ConnMaster);

                                // 更新 t_UserWeixin 
                                m_sql = @"update t_UserWeixin set FMemberID = @FMemberID where FUnionID = @FUnionID and FCorpID = @FCorpID";
                                DBHelper.ExeSQL(m_sql, new List<SqlParameter>() {
                                    new SqlParameter("@FMemberID", m_member_ID),
                                    new SqlParameter("@FUnionID", (userWx[0] as Hashtable)["FUnionID"]),
                                    new SqlParameter("@FCorpID", m_CorpID),
                                }.ToArray(), DBHelper.ConnMaster);
                            }

                            // 更新登录信息
                            m_sql = @"Update dbo.t_UserWeixin Set FCorpID = @FCorpID, FLoginTime = @FLoginTime where FItemID = @FWeixinID;  
                Insert into t_UserWeixinLogin(FWeixinID,FCorpID,FloginTime) values(@FWeixinID,@FCorpID,@FloginTime)";
                            DBHelper.ExeSQL(m_sql, new List<SqlParameter>() {
                                    new SqlParameter("@FCorpID", m_CorpID),
                                    new SqlParameter("@FloginTime", now),
                                    new SqlParameter("@FWeixinID", (userWx[0] as Hashtable)["FItemID"]),
                                }.ToArray(), DBHelper.ConnMaster);

                            // 返回用户信息
                            ht["dt_user"] = DBHelper.Select("select * from t_UserWeixin where FItemID = @FWeixinID", new List<SqlParameter>() {
                                    new SqlParameter("@FWeixinID", (userWx[0] as Hashtable)["FItemID"]),
                            }.ToArray(), DBHelper.ConnMaster)[0];

                            // 返回仓库信息
                            ht["dt_stock"] = DBHelper.Select("select a.*,c.FNumber +' '+c.FName as FCorpName,1 as FStatus   from t_Stock a inner join t_Corpration c on a.FCorpID = c.FItemID where a.FItemID = @FStockID", new List<SqlParameter>() {
                                    new SqlParameter("@FStockID", (userWx[0] as Hashtable)["FStockID"]),
                            }.ToArray(), DBHelper.ConnMaster)[0];

                            // 返回会员信息
                            ht["dt_member"] = DBHelper.Select(" select a.FItemID as MemberId,b.FNumber +' '+ b.FName as CorpName,c.FName as ClassName,a.FName as NiName,a.FNumber as Number,   a.FPoint as Ponit,a.FAmount as Amount,d.FSex as FSex,convert(varchar(10),d.FBirthday,120) as FBirthday, c.FTypeID,a.FDiscount,d.FEmail,convert(varchar(10),d.FEndTime,120) as FEndTime,d.FAddress     from t_Member a left join t_MemberDetail d on d.FItemID=a.FItemID left join  t_MemberClass c on a.FClassID=c.FItemID left join  t_Corpration b on a.FCorpID=b.FItemID    where a.FItemID = @FMemberID", new List<SqlParameter>() {
                                    new SqlParameter("@FMemberID", m_member_ID),
                            }.ToArray(), DBHelper.ConnMaster)[0];


                            //  todo 这里报错
                            /*       if ((ds == null) || (ds.Tables.Count < 2))
                                   {
                                       SystemInfo.writeServiceLog("pr_min_GetMemberLogin", "(ds == null) || (ds.Tables.Count < 2)！", "4", "4D", DBHelper.ConnMaster);
                                       return new Result_Model(status, "缺少参数！");
                                   }

       */
                            /*            DataTable dt_user = ds.Tables[0];
                                        DataTable dt_stock = ds.Tables[1];
                                        DataTable dt_member = ds.Tables[2];*/
                            /*                Hashtable userWeixin = (DBHelper.DataTable2ArrayList(dt_user)?[0]) as Hashtable;
                                            ht["dt_user"] = userWeixin;
                                            ht["dt_stock"] = DBHelper.DataTable2ArrayList(dt_stock)?[0];
                                            ht["dt_member"] = DBHelper.DataTable2ArrayList(dt_member)?[0];*/
                            //m_CorpID = CommonFun.ConvertToInt(userWeixin["FCorpID"]);

                            // 删除多余的
                            /*       string d_sql = "delete from t_UserWeixin    where FLoginTime is  null and  FOpenID=@FOpenID and FCorpID=@FCorpID";
                                   DBHelper.ExeSQL(d_sql, new List<SqlParameter>() {
                                   new SqlParameter("@FOpenID",m_union_id),
                                   new SqlParameter("@FCorpID",m_CorpID)
                                   }.ToArray(), DBHelper.ConnMaster);
                            */



                            if (m_FPhone is null)
                            {

                                Hashtable hs = DBHelper.Select(@"exec  pr_bi_GetMaxAutoIDEx 't_User','FItemID'", DBHelper.ConnMaster)[0] as Hashtable;
                                Int64 m_NewIdentity = 1;

                                Int64? v = hs?["FLastID"] as Int64?;
                                m_NewIdentity = v == null ? 1 : v.Value;
                                string isql = @" 
                                    INSERT INTO [dbo].[t_User] (  [FItemID], [FCorpID], [FClassID], [FNumber], [FName],  [FTelephone], [FPassword],  [FDeleted], [FUses_name],  [FCreatDate],  [FType]) VALUES  (@FItemID, @FCorpID, @FClassID, @FNumber, @FName,  @FTelephone,@FPassword,  @FDeleted, @FUses_name,  @FCreatDate,  @FType);
                                    ";
                                int classId = 0;
                                ltpara = new List<SqlParameter>
                                    {
                                        new SqlParameter("@FItemID", m_NewIdentity),
                                        new SqlParameter("@FCorpID", m_CorpID),
                                        new SqlParameter("@FClassID", classId),
                                        new SqlParameter("@FNumber", m_phone_number),
                                        new SqlParameter("@FName", m_phone_number),
                                        new SqlParameter("@FTelephone", m_phone_number),
                                        new SqlParameter("@FPassword", "Ux/4bRmWcaUiqG5hPfrDPg=="),
                                        new SqlParameter("@FDeleted", 1),
                                        new SqlParameter("@FUses_name", m_phone_number),
                                        new SqlParameter("@FCreatDate", DateTime.Now),
                                        new SqlParameter("@FType", classId),
                                    };
                                DBHelper.ExeSQL(isql, ltpara.ToArray(), DBHelper.ConnMaster);


                                string msql = @"
                                        Update t_UserWeixin set FPhone = @FPhone ,FUserID=@FUserID
                                        where  FUnionID= @FUnionID and  FCorpID=@FCorpID;
                                        ";
                                ltpara = new List<SqlParameter>
                                    {
                                        new SqlParameter("@FPhone", m_phone_number),
                                        new SqlParameter("@FUserID", m_NewIdentity),
                                        new SqlParameter("@FUnionID", (userWx[0] as Hashtable)["FUnionID"]),
                                        new SqlParameter("@FCorpID", m_CorpID),

                                    };
                                DBHelper.ExeSQL(msql, ltpara.ToArray(), DBHelper.ConnMaster);


                                //  return userWeixin
                                var appModel = new SystemAppModel();

                                status = 1;
                                appModel.FCorpID = m_CorpID;
                                appModel.FUserID = (int)m_NewIdentity;  // 用户ID
                                appModel.FStockID = m_stockID;
                                appModel.FOwnerID = 0; //用户组ID
                                appModel.FParentID = FParentID;
                                appModel.FWeixinID = m_FWeixinId.Value;

                                msql = @"SELECT FDbHostIP,FDbSplit,FDbHostNetIP FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}";
                                if (appModel.FParentID > 0)
                                    msql = string.Format(msql, appModel.FParentID);
                                else msql = string.Format(msql, appModel.FCorpID);

                                ArrayList dataAll = DBHelper.Select(msql, DBHelper.ConnMaster);
                                if (dataAll.Count > 0)
                                {
                                    Hashtable record = (Hashtable)dataAll[0];
                                    appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostIP"]);
                                    appModel.FDbSplit = CommonFun.ConvertToString(record["FDbSplit"]);
                                    if (DBHelper.DebugFlag) appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostNetIP"]);
                                }


                                string sSystemAppID = SystemInfo.SetSystemAppID(appModel);
                                ht["systemAppId"] = sSystemAppID;

                                //用户信息
                                ht["userInfo"] = new Dictionary<string, object>() {
                                            { "unionid",m_union_id},
                                            { "openId",(userWx[0] as Hashtable)["FOpenID"]},
                                            { "hasLogin",true},
                                            { "FWeixinID",m_FWeixinId},
                                            { "phone",m_FPhone}
                                };



                                /*  // 门店信息
                                  ht["store"] = new Dictionary<string, object>()
                                  {

                                                     { "hasBindStore",m_CorpId>0}
                                  };*/

                                ArrayList tk = Utils.HashtableToArrayList(ht);
                                return new Result_Model(status, "登录成功！", tk);
                                //return new Result_Model(status, "登录成功！", 33);


                            }
                            else if (m_FPhone == m_phone_number)
                            {

                                //  return userWeixin
                                var appModel = new SystemAppModel();

                                status = 1;
                                appModel.FCorpID = m_CorpID;
                                appModel.FUserID = Convert.ToInt32(m_FUserID);  // 用户ID
                                appModel.FStockID = m_stockID;
                                appModel.FOwnerID = 0; //用户组ID
                                appModel.FParentID = FParentID;
                                appModel.FWeixinID = m_FWeixinId.Value;

                                string msql = @"SELECT FDbHostIP,FDbSplit,FDbHostNetIP FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}";
                                if (appModel.FParentID > 0)
                                    msql = string.Format(msql, appModel.FParentID);
                                else msql = string.Format(msql, appModel.FCorpID);

                                ArrayList dataAll = DBHelper.Select(msql, DBHelper.ConnMaster);
                                if (dataAll.Count > 0)
                                {
                                    Hashtable record = (Hashtable)dataAll[0];
                                    appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostIP"]);
                                    appModel.FDbSplit = CommonFun.ConvertToString(record["FDbSplit"]);
                                    if (DBHelper.DebugFlag) appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostNetIP"]);
                                }


                                string sSystemAppID = SystemInfo.SetSystemAppID(appModel);
                                ht["systemAppId"] = sSystemAppID;

                                //用户信息
                                ht["userWeixin"] = new Dictionary<string, object>() {
                                            { "unionid",m_union_id},
                                            { "openId",(userWx[0] as Hashtable)["FOpenID"]},
                                            { "hasLogin",true},
                                            { "loginByPhone","true"},
                                            { "phone",m_phone_number}
                                        };

                                //用户信息
                                ht["userInfo"] = new Dictionary<string, object>() {
                                            { "unionid",m_union_id},
                                            { "openId",(userWx[0] as Hashtable)["FOpenID"]},
                                            { "hasLogin",true},
                                            { "FWeixinID",m_FWeixinId},
                                            { "phone",m_FPhone}
                                };



                                // 门店信息
                                ht["store"] = new Dictionary<string, object>()
                                {
                                     { "FCorpID",m_CorpID},
                                     { "FStockID",m_stockID},
                                     { "FParentID",FParentID}
                                };

                                ArrayList tk = Utils.HashtableToArrayList(ht);
                                return new Result_Model(status, "登录成功！", tk);

                            }
                            else
                            {
                                SystemInfo.writeServiceLog("该微信已绑定其他号码", "6", "6", "6F", DBHelper.ConnMaster);
                                return new Result_Model(status, "该微信已绑定其他号码！");
                            }
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                SystemInfo.writeServiceLog("result", "手机号获取失败", "5", "5B", DBHelper.ConnMaster);
                return new Result_Model(status, "手机号获取失败！");
            }
        }


        /// <summary>
        /// 获取会员收货信息
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public static ArrayList GetAddressList(int m_CorpID, int m_UserID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select a.*,u.FUserID from t_MemberWeixinInfo a  left  join  t_UserWeixin  u  on  a.FWeixinID=u.FItemID    where u.FUserID = @FUserID   ");
            ltpara.Add(new SqlParameter("@FUserID", m_UserID));
            return DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }


        /// <summary>
        /// 获取会员收货信息
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public static ArrayList GetAddressList(long m_WeixinId)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select *  from t_WxUserAddress     where FWeixinID= @FWeixinID   ");
            ltpara.Add(new SqlParameter("@FWeixinID", m_WeixinId));
            return DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }


        /// <summary>
        /// 获取会员收货信息
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public static ArrayList GetAddressById(long id)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select *  from t_WxUserAddress    where FItemID = @FEntryID");
            ltpara.Add(new SqlParameter("@FEntryID", id));
            return DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }


        /// <summary>
        /// 保存收货地址
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static bool SaveAddress(string strJson, long m_WeixinID)
        {
            ArrayList userWechat = DBHelper.Select("SELECT * FROM  t_UserWeixin where FItemID =@FItemID", new List<SqlParameter>() {
            new SqlParameter("@FItemID",m_WeixinID)
            }.ToArray(), DBHelper.ConnMaster);
            if (userWechat.Count is 0)
            {
                return false;
            }

            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();

            t_WxUserAddress _mode = JsonConvert.DeserializeObject<t_WxUserAddress>(strJson);
            _mode.FWeixinID = m_WeixinID;
            int m_address_count = DBHelper.Select("select  FItemID   from  t_WxUserAddress where FWeixinID=@FWeixinID", new List<SqlParameter>() {
                new SqlParameter("@FWeixinID", _mode.FWeixinID)
                }.ToArray(), DBHelper.ConnMaster).Count;



            if (_mode.FItemID <= 0)
            {

                /*          strSql.Append(@"Insert Into t_WxUserAddress(FItemID,FWeixinID,FPhone,FAddress,FZipcode,FConsignee,FPrCityArea,FPrvID,FCityID,FAreaID,FDefault)
                            values (@FItemID,@FWeixinID,@FPhone,@FAddress,@FZipcode,@FConsignee,@FPrCityArea,@FPrvID,@FCityID,@FAreaID,@FDefault)");*/
                strSql.Append(@"Insert Into t_WxUserAddress(FWeixinID,FPhone,FAddress,FZipcode,FConsignee,FPrCityArea,FPrvID,FCityID,FAreaID,FDefault)
                            values (@FWeixinID,@FPhone,@FAddress,@FZipcode,@FConsignee,@FPrCityArea,@FPrvID,@FCityID,@FAreaID,@FDefault)");
                Hashtable hs = DBHelper.Select(@"exec  pr_bi_GetMaxAutoIDEx 't_MemberWeixinInfo','FItemID'", DBHelper.ConnMaster)[0] as Hashtable;
                Int64? v = hs?["FLastID"] as Int64?;
                Int64 m_NewIdentity = v == null ? 1 : v.Value;
                if (m_address_count == 0)
                {
                    _mode.FDefault = "1";
                }
                else if (_mode.FDefault == "1")
                {
                    DBHelper.ExeSQL(@"update t_WxUserAddress set  FDefault='0'  where FWeixinID=@FWeixinID ", new List<SqlParameter>() { new SqlParameter("@FWeixinID", _mode.FWeixinID) }.ToArray(), DBHelper.ConnMaster);
                }
                //ltpara.Add(new SqlParameter("@FItemID", m_NewIdentity));
                ltpara.Add(new SqlParameter("@FWeixinID", _mode.FWeixinID));
                ltpara.Add(new SqlParameter("@FPhone", _mode.FPhone));
                ltpara.Add(new SqlParameter("@FAddress", _mode.FAddress));
                ltpara.Add(new SqlParameter("@FZipcode", _mode.FZipcode));
                ltpara.Add(new SqlParameter("@FConsignee", _mode.FConsignee));
                ltpara.Add(new SqlParameter("@FPrCityArea", _mode.FPrCityArea));
                ltpara.Add(new SqlParameter("@FPrvID", _mode.FPrvID));
                ltpara.Add(new SqlParameter("@FCityID", _mode.FCityID));
                ltpara.Add(new SqlParameter("@FAreaID", _mode.FAreaID));
                ltpara.Add(new SqlParameter("@FDefault", _mode.FDefault));
                DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);

            }
            else
            {
                if (m_address_count == 1)
                {
                    _mode.FDefault = "1";
                }
                strSql.Append(@"Update t_WxUserAddress set FPhone = @FPhone,FAddress = @FAddress,FZipcode = @FZipcode,FConsignee = @FConsignee,
                  FPrvID = @FPrvID,FCityID = @FCityID,FAreaID = @FAreaID,FPrCityArea = @FPrCityArea,FDefault=@FDefault where FItemID = @FItemID");
                ltpara.Add(new SqlParameter("@FPhone", _mode.FPhone));
                ltpara.Add(new SqlParameter("@FAddress", _mode.FAddress));
                ltpara.Add(new SqlParameter("@FZipcode", _mode.FZipcode));
                ltpara.Add(new SqlParameter("@FConsignee", _mode.FConsignee));
                ltpara.Add(new SqlParameter("@FPrvID", _mode.FPrvID));
                ltpara.Add(new SqlParameter("@FCityID", _mode.FCityID));
                ltpara.Add(new SqlParameter("@FAreaID", _mode.FAreaID));
                ltpara.Add(new SqlParameter("@FPrCityArea", _mode.FPrCityArea));
                ltpara.Add(new SqlParameter("@FItemID", _mode.FItemID));
                ltpara.Add(new SqlParameter("@FDefault", _mode.FDefault));
                if (m_address_count <= 1)
                {
                    _mode.FDefault = "1";
                }
                else
                {
                    DBHelper.ExeSQL(@"update t_WxUserAddress set  FDefault='0'  where FWeixinID=@FWeixinID ", new List<SqlParameter>() { new SqlParameter("@FWeixinID", _mode.FWeixinID) }.ToArray(), DBHelper.ConnMaster);
                }

                DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);


            }


            /*     if (DBHelper.ExeSQL(strSql, ltpara.ToArray()))
                 {
                     return true;
                 }
                 return false;*/
            return true;
        }

        /*/// <summary>
        /// 删除收货地址
        /// </summary>
        /// <param name="FEntryID"></param>
        /// <returns></returns>
        public static bool DelAddress(long FEntryID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"delete from t_MemberWeixinInfo where FEntryID = @FEntryID");
            ltpara.Add(new SqlParameter("@FEntryID", FEntryID));

            DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            List<SqlParameter> ltpara2 = new List<SqlParameter>();
            ltpara2.Add(new SqlParameter("@FEntryID", FEntryID));
            string sql = @"select * from t_MemberWeixinInfo where FEntryID = @FEntryID";
            return DBHelper.Select(sql, ltpara2.ToArray(), DBHelper.ConnMaster).Count <= 0;

        }*/

        /// <summary>
        /// 删除收货地址
        /// </summary>
        /// <param name="FEntryID"></param>
        /// <returns></returns>
        public static bool DelAddress(long FEntryID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"delete from t_WxUserAddress where FItemID = @FItemID");
            ltpara.Add(new SqlParameter("@FItemID", FEntryID));

            DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            List<SqlParameter> ltpara2 = new List<SqlParameter>();
            ltpara2.Add(new SqlParameter("@FItemID", FEntryID));
            string sql = @"select * from t_WxUserAddress where FItemID = @FItemID";
            return DBHelper.Select(sql, ltpara2.ToArray(), DBHelper.ConnMaster).Count <= 0;

        }

        public static ArrayList GetPay() => DBHelper.Select(@"select * from t_Payment_Mall where FStatus = 1", DBHelper.ConnMaster);

        /// <summary>
        /// 获取购物车商品数据
        /// </summary>
        /// <returns></returns>
        public static DataTable GetShopCart(long FWeixinID, long FCorpID, int FImportFlag = -1)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select a.FEntryID,a.FCorpID,a.FGoodsID,b.FName,b.FSpec,CONVERT(float,a.FQty) as FQty,a.FIntegral,
            CONVERT(numeric(18,2),a.FPrice) as FPrice,CONVERT(numeric(18,2),b.FPosPrice) as FPosPrice,c.FBulk,
            CONVERT(numeric(18,2),a.FQty * a.FPrice) as RealMoney,b.FImportFlag,isnull(c.FWeight,0) as FWeight,
            (select top 1 REPLACE(col,'/'+CAST(1 as varchar)+'/','/'+CAST(1 as varchar)+'/Thumb/') as tcol from dbo.f_split(c.FProImage,'$')) as FThumbImage
            from y_Mall_Shopping a inner join t_Goods b on a.FGoodsID = b.FItemID left join t_GoodsDetail c on b.FItemID = c.FItemID
            where a.FWeixinID = @FWeixinID and a.FCorpID = @FCorpID");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            if (FImportFlag >= 0)
            {
                strSql.Append(" and b.FImportFlag = @FImportFlag");
                ltpara.Add(new SqlParameter("@FImportFlag", FImportFlag));
            }
            return DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }

        public static int GetGoodsListCount(int mCorpID, int mClassID, int mBrandID, string mConditon, int mOrderType)
        {
            int count = 0;
            StringBuilder sb = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();

            sb.Append("select count(a.FItemID) as count  FROM dbo.t_GoodsMall AS m INNER JOIN         dbo.t_Goods AS a ON m.FGoodsID = a.FItemID INNER JOIN t_GoodsDetail b on a.FItemID = b.FItemID         where a.FDeleted = 1 and m.FMallFlag = 1 and m.FCorpID =@mCorpID ");
            ltpara.Add(new SqlParameter("@mCorpID", mCorpID));
            if (mClassID > 0)
            {
                sb.Append(" and a.FClassID in (select FItemID from dbo.f_GetSonNode( @m_Member_Class_ID ))");
                ltpara.Add(new SqlParameter("@m_Member_Class_ID", mClassID));
            }
            if (@mConditon != "")
            {
                string condition = "%" + mConditon + "%";

                // 现在我们可以安全地添加一个带有正确参数的SQL片段  
                sb.Append(" and a.FName like @mConditonWithWildcard");
                // 注意我们创建了一个新的参数名，因为它包含了通配符  
                ltpara.Add(new SqlParameter("@mConditonWithWildcard", condition));
            }

            Hashtable res = DBHelper.Select(sb.ToString(), ltpara.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            count = (int)res["count"];

            return count;
        }

        public static ArrayList GetCouponList(int m_CorpID, long m_MemberId, int type)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"SELECT     c.FClassID,c.FName,c.FValue,c.FMinValue,c.FMaxValue,c.FDeleted,c.FRemark,c.FModifyTime,c.FCreateTime,c.FLogoUrl,c.FNotice,c.FDescription,c.FCardID,c.FAutoSendFlag,c.FDateType,c.FStartDate,c.FEndDate,c.FDays,c.FStoreFlag,c.FOnlineFlag,c.FMaxCount,c.FUsedCount,c.FActiveStartDate,c.FActiveEndDate,c.FSelectType,
s.FItemID,s.FCorpID, s.FCouponID, s.FNumber, s.FSendUserID,s.FMemberID,s.FSendTime,s.FStartTime,s.FEndTime,s.FPassword,s.FStatus,s.FAmount,s.FDeleted,s.FBillNo,s.FUseTime,s.FRemark,s.FCreateDate,s.FBatchID,s.FIntegral,s.FromBillNo,s.FActStartTime,s.FActEndTime,s.FCouponType, cl.FName as FClassName
      FROM y_CouponSend s 
      LEFT OUTER JOIN t_Coupon c on c.FItemID=s.FCouponID 
      LEFT OUTER JOIN t_CouponClass cl on c.FClassID=cl.FItemID 
      WHERE FMemberID=@FMemberID and  s.FCorpID=@FCorpID  ");
            switch (type)
            {
                case 0:
                    {
                        strSql.Append("  and s.FStatus=0   and s.FEndTime > GETDATE() ");
                        break;
                    };
                case 1:
                    {
                        strSql.Append("  and s.FStatus=1   ");
                        break;
                    };
                case 2:
                    {
                        strSql.Append("  and s.FStatus=0   and s.FEndTime <= GETDATE() ");
                        break;
                    };
                default:
                    break;
            }

            ltpara.Add(new SqlParameter("@FMemberID", m_MemberId));
            ltpara.Add(new SqlParameter("@FCorpID", m_CorpID));
            ArrayList arrayList = DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            foreach (var item in arrayList)
            {
                Hashtable coupon = (Hashtable)item;
                long m_FCouponID = (long)coupon["FCouponID"];

                List<SqlParameter> ltparas = new List<SqlParameter>();
                ltparas.Add(new SqlParameter("@FCorpID", m_CorpID));
                ltparas.Add(new SqlParameter("@FCouponID", m_FCouponID));

                string m_sql = "SELECT cg.FGoodID,cg.FCouponID,g.* FROM t_CouponGoods cg LEFT JOIN  t_Goods  g ON  g.FItemID=cg.FGoodID WHERE cg.FCorpID=@FCorpID  and cg.FCouponID=@FCouponID";
                coupon["goodsList"] = DBHelper.Select(m_sql, ltparas.ToArray(), DBHelper.ConnMaster);
            }


            return arrayList;
        }

        public static ArrayList GetCouponById(int m_CorpID, long m_MemberId, long id)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"SELECT     c.FClassID,c.FName,c.FValue,c.FMinValue,c.FMaxValue,c.FDeleted,c.FRemark,c.FModifyTime,c.FCreateTime,c.FLogoUrl,c.FNotice,c.FDescription,c.FCardID,c.FAutoSendFlag,c.FDateType,c.FStartDate,c.FEndDate,c.FDays,c.FStoreFlag,c.FOnlineFlag,c.FMaxCount,c.FUsedCount,c.FActiveStartDate,c.FActiveEndDate,c.FSelectType,
s.FItemID,s.FCorpID, s.FCouponID, s.FNumber, s.FSendUserID,s.FMemberID,s.FSendTime,s.FStartTime,s.FEndTime,s.FPassword,s.FStatus,s.FAmount,s.FDeleted,s.FBillNo,s.FUseTime,s.FRemark,s.FCreateDate,s.FBatchID,s.FIntegral,s.FromBillNo,s.FActStartTime,s.FActEndTime,s.FCouponType, cl.FName as FClassName
      FROM y_CouponSend s 
      LEFT OUTER JOIN t_Coupon c on c.FItemID=s.FCouponID 
      LEFT OUTER JOIN t_CouponClass cl on c.FClassID=cl.FItemID 
      WHERE FMemberID=@FMemberID and  s.FCorpID=@FCorpID and  s.FCouponID=@FCouponID");

            ltpara.Add(new SqlParameter("@FMemberID", m_MemberId));
            ltpara.Add(new SqlParameter("@FCorpID", m_CorpID));
            ltpara.Add(new SqlParameter("@FCouponID", id));
            ArrayList arrayList = DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            foreach (var item in arrayList)
            {
                Hashtable coupon = (Hashtable)item;
                long m_FCouponID = (long)coupon["FCouponID"];

                List<SqlParameter> ltparas = new List<SqlParameter>();
                ltparas.Add(new SqlParameter("@FCorpID", m_CorpID));
                ltparas.Add(new SqlParameter("@FCouponID", m_FCouponID));

                string m_sql = "SELECT cg.FGoodID,cg.FCouponID,g.* FROM t_CouponGoods cg LEFT JOIN  t_Goods  g ON  g.FItemID=cg.FGoodID WHERE cg.FCorpID=@FCorpID  and cg.FCouponID=@FCouponID";
                coupon["goodsList"] = DBHelper.Select(m_sql, ltparas.ToArray(), DBHelper.ConnMaster);
            }


            return arrayList;
        }

        public static void Base64StringToImage(string strbase64, string path)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);

                bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                ms.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 股东拓客礼名分享码
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static async Task<Result_Model> GetQrCode(string scene)
        {
            int status = 0;
            string page = "pages/tab_bar/index";
            //var fileNameStr = CommonHelper.Md5For32(m_CorpID.ToString()) + CommonHelper.Msectime();
            var fileNameStr = scene;
            //QrCode 根目录
            var dir = "/Upload/weChat/";
            //文件虚拟目录
            //var fileName = dir + fileNameStr + ".jpg";
            //文件硬地址
            string appDir = HostingEnvironment.ApplicationPhysicalPath;
            var qrCodeDir = appDir + dir;
            //QrCode 文件全路径
            var pathFileName = qrCodeDir + fileNameStr + ".png";
            var relDir = dir + fileNameStr + ".png";
            //文件硬地址
            Dictionary<string, object> m_access_resp = await MallService.GetAccessTokenAsync("wxf7ce08d94685bf3e");
            string m_access_token = m_access_resp?["access_token"] as string;
            SystemInfo.writeServiceLog(m_access_token, "A", "1009", "1", DBHelper.ConnMaster);


            //设置Http的正文
            //MemoryStream ms;

            try
            {
                // 准备要发送的JSON数据  
                var jsonData = new
                {
                    scene,
                    page
                };
                SystemInfo.writeServiceLog("getwxacodeunlimit", "B", "1009", "1", DBHelper.ConnMaster);
                SystemInfo.writeServiceLog("getwxacodeunlimit", "B", "1009", "1", DBHelper.ConnMaster);

                //// 发送POST请求  
                // byte[] bytes = await $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={m_access_token}".AllowAnyHttpStatus().PostJsonAsync(jsonData).ReceiveBytes();
                //string str = await $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={m_access_token}".AllowAnyHttpStatus().PostJsonAsync(jsonData).ReceiveString();
                string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + m_access_token;
                string dataJson = "{";
                dataJson += string.Format("\"scene\":\"{0}\",", scene);//所要传的参数用,分看
                dataJson += string.Format("\"page\":\"{0}\"", page);//扫码所要跳转的地址，根路径前不要填加'/',不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
                dataJson += "}";
                byte[] inArray = HttpService.PostMoths(url, dataJson);
                string str = /*"data:image/png;base64," +*/ Convert.ToBase64String(inArray);
                if (!Directory.Exists(qrCodeDir))
                {
                    Directory.CreateDirectory(qrCodeDir);
                }

                Base64StringToImage(str, pathFileName);
                SystemInfo.writeServiceLog(str, "C", "1009", "1", DBHelper.ConnMaster);
                /*          try
                          {
                              //string str = Encoding.UTF8.GetString(bytes);
                              SystemInfo.writeServiceLog("getwxacodeunlimit", str, "1", "1", DBHelper.ConnMaster);

                          }
                          catch (Exception e)
                          {
                              SystemInfo.writeServiceLog("getwxacodeunlimit", e.ToString(), "1", "2", DBHelper.ConnMaster);
                              throw;
                          }*/


                //ms = new MemoryStream(bytes);
                //QrCode 根目录

                /*       FileStream fs = new FileStream(pathFileName, FileMode.OpenOrCreate);
                       BinaryWriter w = new BinaryWriter(fs);
                       //w.Write(ms.ToArray());
                       fs.Close();*/
                //ms.Close();
                status = 1;
                return new Result_Model(status, "获取成功!", new
                {
                    relDir
                });

            }
            catch (Exception e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            return new Result_Model(status, "获取失败!", new
            {
                msg = "获取失败"
            });

        }
        public static byte[] ReadStreamToByteArray(Stream stream)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }
        /// <summary>
        ///  获取微信 Access_Token
        /// </summary>
        /// <returns></returns>
        public static async Task<Dictionary<string, object>> GetAccessTokenAsync(string appId)
        {
            string secret = GetAppSecret(appId);
            Dictionary<string, object> res = null;
            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";
                    HttpResponseMessage response = await httpClient.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string dt = await response.Content.ReadAsStringAsync();
                    res = JsonConvert.DeserializeObject<Dictionary<string, object>>(dt);
                }
                catch (HttpRequestException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return res;
        }
        /// <summary>
        /// 通过appid获取密钥
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        public static string GetAppSecret(string appid)
        {
            string sql = @"select FAppSecret from t_MiniSetting where FAppID=@FAppID";
            SqlParameterList parlist = new SqlParameterList();
            parlist.Add("@FAppID", SqlDbType.VarChar, appid);
            DataTable dt = DBHelper.GetDataTable(sql, parlist.Get_List(), DBHelper.ConnMaster);

            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                return CommonFun.ConvertToString(dr["FAppSecret"]);
            }
            return "";
        }


        public static long GetMaxAutoID(string strTablename, string strFieldname)
        {
            List<SqlParameter> ltPar = new List<SqlParameter>()
            {
                new SqlParameter("@strTablename",strTablename),
                new SqlParameter("@strFieldname",strFieldname),
            };
            Hashtable hs = DBHelper.Select(@"exec  pr_bi_GetMaxAutoIDEx @strTablename,@strFieldname", ltPar.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            Int64? v = hs?["FLastID"] as Int64?;
            return v == null ? 1 : v.Value;
        }



        public static bool SetDefaultAddress(long m_FItemID, long m_WeixinID)
        {

            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select  FItemID from t_WxUserAddress where FItemID = @FItemID");
            ltpara.Add(new SqlParameter("@FItemID", m_FItemID));

            if (DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster).Count != 1)
            {
                return false;
            };
            string sql = @"
                update t_WxUserAddress set  FDefault='0'  where FWeixinID=@FWeixinID ;
                update t_WxUserAddress set  FDefault='1'  where FItemID = @FItemID and FWeixinID=@FWeixinID";
            List<SqlParameter> ltpara2 = new List<SqlParameter>();
            ltpara2.Add(new SqlParameter("@FItemID", m_FItemID));
            ltpara2.Add(new SqlParameter("@FWeixinID", m_WeixinID));
            try
            {
                DBHelper.ExeSQL(sql, ltpara2.ToArray(), DBHelper.ConnMaster);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}



